﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Xml.Linq;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using Microsoft.Phone.Info;

namespace Ads
{
    public class AdsHelper
    {
        public string phonename = "";  //机型名称
        public string phonevs = "WindowsPhone"; //机型系统版本
        public string phonevsno = ""; //机型系统版本号
        public string keyvalue = ""; //[缺省]加密字串,识别正确访问码
        public string imei = ""; //手机串号
        public int downclassid = 0; //资源分类ID，1、软件；2、游戏；3、主题
        public int downinfoid = 0; //资源ID
        public string channelkey = ""; //渠道
        public string softvs = ""; //软件版本
        public string network = "mobile"; //网络接入方式,包括cmwap、cmnet、wifi、3gwap等
        public string softid = ""; //软件ID
        public string flatid = "2"; //平台ID
        public int p = 1; //分页页码,默认1
        public int pagesize = 20; //分页大小
        public string total = ""; //总记录数 可有可无
        public string order = "2"; //排序方式,1、最新；2、最热
        public string pos = "1"; //显示位置,0、列表；1、首页
        public string appid = "";


        public delegate void InitRequest();
        public event InitRequest OnInitRequest;

        public delegate void GetAdsRequest(AdsModels ads);
        public event GetAdsRequest OnGetAdsRequest;

        public delegate void GetAdsDetail(AdsModel ad);
        public event GetAdsDetail OnGetAdDetailRequest;

        public AdsHelper(string _appid, string _channelkey, string _softid, string _softvs, string _keyvalue)
        {
            appid = _appid;
            channelkey = _channelkey;
            imei = MD5Helper.GetMd5String(BitConverter.ToString(
                    (byte[])DeviceExtendedProperties.GetValue("DeviceUniqueId")
                    ));
            softid = _softid;
            phonename = DeviceExtendedProperties.GetValue("DeviceName").ToString();
            phonevsno = Environment.OSVersion.Version.ToString();
            softvs = _softvs;
            keyvalue = _keyvalue;
        }

        public void AdsInit()
        {
            string InitUrl =
                    String.Format(("http://112.65.245.231/cpic/init.aspx?phonename={0}&phonevs={1}&phonevsno={2}" +
                    "&keyvalue={3}&imei={4}&downclassid={5}&downinfoid={6}&channelkey={7}" +
                    "&softvs={8}&network={9}&softid={10}&flatid={11}"), phonename, phonevs, phonevsno,
                     keyvalue, imei, downclassid, downinfoid, channelkey, softvs,
                     network, softid, flatid);
            WebClient webClient = new WebClient();
            webClient.OpenReadCompleted += (s, e) =>
            {
                if (e.Error != null) return;
                using (Stream streamResult = e.Result)
                {
                    XElement root = XElement.Load(streamResult);
                    var tests = from el in root.Elements("display") select el;
                    foreach (var a in tests)
                    {
                        if (a.Value == "1")   //得到数据，并display为1时才触发事件
                        {
                            OnInitRequest();
                            break;
                        }
                    }
                }
            };
            webClient.OpenReadAsync(new Uri(InitUrl), webClient);
        }

        public void GetAds(int _pos, int _p, int _order)  //pos为0是列表，1是首页
        {
            string IndexUrl = String.Format("http://112.65.245.231/cpic/adlist.aspx?phonename={0}&phonevs={1}" +
                "&phonevsno={2}&keyvalue={3}&imei={4}&downclassid={5}&downinfoid={6}&channelkey={7}&softvs={8}" +
                "&network={9}&p={10}&pagesize={11}&total={12}&order={13}&pos={14}&softid={15}&flatid={16}", phonename, phonevs,
                phonevsno, keyvalue, imei, downclassid, downinfoid, channelkey, softvs,
                network, _p, pagesize, total, _order, _pos, softid, flatid);
            WebClient webClient = new WebClient();
            webClient.OpenReadCompleted += (s, e) =>
            {
                if (e.Error != null)
                {
                    if (_pos == 0) MessageBox.Show("网络无法连接，请重试！");
                    OnGetAdsRequest(new AdsModels());
                    return;
                }
                using (Stream streamResult = e.Result)
                {
                    XElement root = XElement.Load(streamResult);
                    var tests = from el in root.Elements("resultinfo") select el;
                    foreach (var a in tests)
                    {
                        if (a.Attribute("result").Value == "1")   //成功
                        {
                            var adinfo = from el in root.Elements("adinfo") select el;
                            List<AdsModel> lst = new List<AdsModel>();
                            foreach (var ad in adinfo) //遍历adinfo
                            {
                                lst.Add(new AdsModel()
                                {
                                    imgUrl = ad.Element("icon").Value,
                                    url = "http://rrsee.net/cpic/downstat.aspx?appid=" + ad.Attribute("appid").Value,
                                    title = ad.Element("title").Value.ToString(),
                                    appid = ad.Attribute("appid").Value,
                                    downcount = ad.Attribute("downcount").Value,
                                    scores = Convert.ToInt32(ad.Attribute("score").Value)
                                });
                            }
                            AdsModels ads = new AdsModels();
                            ads.list = lst;
                            var page = from el in root.Elements("page") select el;
                            foreach (var pe in page) //遍历adinfo
                            {
                                ads.isnextpage = pe.Attribute("isnextpage").Value;
                                ads.p = Convert.ToInt32(pe.Attribute("isnextpage").Value);
                            }
                            OnGetAdsRequest(ads); //触发回调事件 返回广告列表
                        }
                        break;
                    }
                }
            };
            webClient.OpenReadAsync(new Uri(IndexUrl), webClient);
        }

        public void GetDetail(string _appid)
        {
            string DetailUrl = String.Format("http://112.65.245.231/cpic/content.aspx?phonename={0}&phonevs={1}&" +
                "phonevsno={2}&keyvalue={3}&imei={4}&downclassid={5}&downinfoid={6}&channelkey={7}&softvs={8}&network={9}&" +
                "isad={10}&flatid={11}",
                phonename, phonevs,
                phonevsno, keyvalue, imei, downclassid, downinfoid, channelkey, softvs, network,
                1, flatid);
            WebClient webClient = new WebClient();
            webClient.OpenReadCompleted += (s, e) =>
            {
                if (e.Error != null)
                {
                    MessageBox.Show("网络无法连接，请重试！"); OnGetAdDetailRequest(null);
                    return;
                }
                using (Stream streamResult = e.Result)
                {
                    XElement root = XElement.Load(streamResult);
                    var tests = from el in root.Elements("resultinfo") select el;
                    foreach (var t in tests)
                    {
                        if (t.Attribute("result").Value == "1")   //成功
                        {
                            AdsModel a = new AdsModel();
                            var content = from el in root.Elements("content") select el;
                            foreach (var ad in content)
                            {
                                a.imgUrl = ad.Element("icon").Value;
                                a.title = ad.Element("title").Value.ToString();
                                a.scores = Convert.ToInt32(ad.Element("score").Value);
                                a.text = ad.Element("remark").Value;
                                a.size = ad.Element("filesize").Value;
                                string filename = ad.Element("downurl").Value;
                                if (filename.Length == 36 && filename.Substring(8, 1) == "-")
                                    a.url = filename;
                                else
                                    a.url = "http://rrsee.net/cpic/downstat.aspx?appid=" + _appid;
                            }
                            var imgfile = from el in root.Elements("imgfile") select el;
                            List<string> lst = new List<string>();
                            foreach (var img in imgfile)
                                lst.Add(img.Element("imgurl").Value);
                            a.screen = lst;
                            OnGetAdDetailRequest(a); //触发回调事件 返回广告详情
                        }
                        else
                            OnGetAdDetailRequest(null);
                        break;
                    }
                }
            };
            webClient.OpenReadAsync(new Uri(DetailUrl), webClient);
        }

    }
}
